//
//  PrivateLetterContentController.m
//  collection
//
//  Created by 靖 张 on 12/15/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "PrivateLetterContentController.h"
#import "CollectionDataManager.h"
#import "PrivateLetterItem.h"
#import "Utility.h"

#define SENDER_CELLID   @"SenderCell"
#define RECEIVER_CELLID @"ReceiverCell"

@interface PrivateLetterContentController()

@property (nonatomic, strong)   NSMutableArray* letterList;
@property (retain, nonatomic) IBOutlet UILabel *navTitle;
@property (retain, nonatomic) IBOutlet UIView *composeView;
@property (retain, nonatomic) IBOutlet UITextView *letterView;
@property (retain, nonatomic) IBOutlet UITableView *letterTableView;

- (IBAction)onClickBackBarItem:(id)sender;
- (IBAction)onClickSendButton:(id)sender;

- (void)keyboardWillShow:(NSNotification*) notification;
- (void)keyboardWillHide:(NSNotification*) notification;

@end

@implementation PrivateLetterContentController

@synthesize letterList = _letterList;
@synthesize navTitle = _navTitle;
@synthesize composeView = _composeView;
@synthesize letterView = _letterView;
@synthesize letterTableView = _letterTableView;
@synthesize conversationObjectUID = _conversationObjectUID;
@synthesize isEditMode = _isEditMode;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.hidesBottomBarWhenPushed = YES;
        _userID = 1;
        
        // Register keyboard event handler
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        
        NSMutableArray* letterList = [[NSMutableArray alloc] initWithCapacity:1];
        self.letterList = letterList;
        [letterList release];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.letterList = nil;
    [_navTitle release];
    [_composeView release];
    [_letterView release];
    [_letterTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    NSDictionary* letterSet = sharedDataManager.privateLetterSet;
    NSArray* threads = [letterSet objectForKey:[NSString stringWithFormat:@"%lld", _userID]];
    for (PrivateLetterThread* oneThread in threads) {
        if (oneThread.objectID == self.conversationObjectUID) {
            self.letterList = oneThread.letterList;
            break;
        }
    }
    
    [self.letterTableView reloadData];
    
    NSLog(@"View will appear");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    UserInfo* user = [sharedDataManager cacheUserByUserID:self.conversationObjectUID];
    self.navTitle.text = user.nickname;
    NSLog(@"UID : %lld\nUName : %@", self.conversationObjectUID, user.nickname);
    
    NSLog(@"View did load");
    
    UIView* emptyView = [[UIView alloc] init];
    emptyView.backgroundColor = [UIColor clearColor];
    self.letterTableView.tableFooterView = emptyView;
    [emptyView release];
    
    if (self.isEditMode) {
        [self.letterView becomeFirstResponder];
    }
}

- (void)viewDidUnload
{
    [self setNavTitle:nil];
    [self setComposeView:nil];
    [self setLetterView:nil];
    [self setLetterTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.letterList = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Implementation of UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.letterList != nil &&
        [self.letterList count] > 0) {
        return 1;
    }
    else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.letterList count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    PrivateLetterItem* item = [self.letterList objectAtIndex:indexPath.row];
    UserInfo* user = [sharedDataManager cacheUserByUserID:item.senderID];
    UITableViewCell* cell;
    if (item.senderID == _userID) {
        static NSString* cellID = SENDER_CELLID;
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"PrivateLetterSenderCell" owner:self options:nil];
            cell = [views objectAtIndex:0];
            UIView* bgView = [[UIView alloc] initWithFrame:cell.frame];
            bgView.backgroundColor = [UIColor colorWithRed:229.0 / 255.0 green:229.0 / 255.0 blue:229.0 / 255.0 alpha:1];
            cell.selectedBackgroundView = bgView;
            [bgView release];
        }
    }
    else {
        static NSString* cellID = RECEIVER_CELLID;
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"PrivateLetterReceiverCell" owner:self options:nil];
            cell = [views objectAtIndex:0];
            UIView* bgView = [[UIView alloc] initWithFrame:cell.frame];
            bgView.backgroundColor = [UIColor colorWithRed:229.0 / 255.0 green:229.0 / 255.0 blue:229.0 / 255.0 alpha:1];
            cell.selectedBackgroundView = bgView;
            [bgView release];
        }
    }
 
    CGRect frame;
    // Avatar
    UIImageView* avatarView = (UIImageView*)[cell viewWithTag:1];
    avatarView.image = user.avatar;
    
    // Text
    UILabel* content = (UILabel*)[cell viewWithTag:2];
    content.text = item.text;
    [content sizeToFit];
    
    
    // Time stamp
    UILabel* tsLabel = (UILabel*)[cell viewWithTag:3];
    tsLabel.text = [Utility transTimeToCurrentFormat:item.publishTime];
    frame = tsLabel.frame;
    frame.origin.y = content.frame.origin.y + content.frame.size.height;
    tsLabel.frame = frame;
    
    // Cell height
    frame = cell.frame;
    frame.size.height = content.frame.origin.y + content.frame.size.height + tsLabel.frame.size.height;
    cell.frame = frame;
    
    return cell;
}

#pragma mark - Impelementation of UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

#pragma mark - Private methods

- (IBAction)onClickBackBarItem:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    //    self.navigationController.navigationBarHidden = YES;
}

- (IBAction)onClickSendButton:(id)sender {
    
    NSString* letterContent = self.letterView.text;
    if ([letterContent isEqualToString:@""]) {
        return;
    }
    
    PrivateLetterItem* newLetter = [[PrivateLetterItem alloc] init];
    newLetter.senderID  = _userID;
    newLetter.receiverID = self.conversationObjectUID;
    newLetter.text = letterContent;
    newLetter.publishTime = [NSDate date];

    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    NSDictionary* letterSet = sharedDataManager.privateLetterSet;
    NSMutableArray* threads = [letterSet objectForKey:[NSString stringWithFormat:@"%lld", _userID]];
    
    if (threads == nil) {
        
    }
    
    PrivateLetterThread* theThread = nil;
    for (PrivateLetterThread* oneThread in threads) {
        if (oneThread.objectID == self.conversationObjectUID) {
            theThread = oneThread;
            break;
        }
    }
    
    if (theThread == nil) {
        theThread = [[PrivateLetterThread alloc] init];
        NSMutableArray* letterList = [[NSMutableArray alloc] initWithCapacity:1];
        theThread.userID = _userID;
        theThread.objectID = self.conversationObjectUID;
        UserInfo* objectUser = [sharedDataManager cacheUserByUserID:self.conversationObjectUID];
        theThread.objectAvatarURL = objectUser.avatarURL;
        theThread.letterList = letterList;
        [letterList release];
        
        [threads addObject:theThread];
    }
    
    NSMutableArray* letterList = theThread.letterList;
    if (letterList != nil) {
        [letterList addObject:newLetter];
        [newLetter release];
    }
    
    // Resort
    [theThread retain];
    [threads removeObject:theThread];
    [threads insertObject:theThread atIndex:0];
    [theThread release];
    
    self.letterList = letterList;
    [self.letterTableView reloadData];
    
    self.letterView.text = @"";
    [self.letterView resignFirstResponder];
    
    NSInteger sectionNum = [self.letterTableView numberOfSections];  
    if (sectionNum < 1) return;  
    NSInteger rowNum = [self.letterTableView numberOfRowsInSection:sectionNum - 1];  
    if (rowNum < 1) return;  
    
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:rowNum - 1 inSection:sectionNum - 1];
    
    [self.letterTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)keyboardWillShow:(NSNotification *) notification {
    NSDictionary *info = [notification userInfo];
    
    NSValue* value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    CGRect frame = self.letterTableView.frame;
    frame.size.height -= keyboardSize.height;
    self.letterTableView.frame = frame;
    
    frame = self.composeView.frame;
    frame.origin.y -= keyboardSize.height;
    self.composeView.frame = frame;
}

- (void)keyboardWillHide:(NSNotification *) notification {
    NSDictionary *info = [notification userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    CGRect frame = self.letterTableView.frame;
    frame.size.height += keyboardSize.height;
    self.letterTableView.frame = frame;
    
    frame = self.composeView.frame;
    frame.origin.y += keyboardSize.height;
    self.composeView.frame = frame;
}

@end
